package com.yoda.mall.mysql.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yoda.mall.api.RoleMenuRelationApi;
import com.yoda.mall.model.entity.ums.AdminRoleRelation;
import com.yoda.mall.model.entity.ums.Menu;
import com.yoda.mall.model.entity.ums.RoleMenuRelation;
import com.yoda.mall.mysql.mapper.AdminRoleRelationMapper;
import com.yoda.mall.mysql.mapper.MenuMapper;
import com.yoda.mall.mysql.mapper.RoleMenuRelationMapper;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shawn
 * @date 2022年 12月 16日 11:33
 */
@DubboService
public class RoleMenuRelationApiImpl implements RoleMenuRelationApi {
    @Resource
    private RoleMenuRelationMapper roleMenuRelationMapper;

    @Resource
    private AdminRoleRelationMapper adminRoleRelationMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> listMenuByRoleId(Integer roleId) {
        LambdaQueryWrapper<RoleMenuRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenuRelation::getRoleId,roleId);
        List<RoleMenuRelation> roleMenuRelations = roleMenuRelationMapper.selectList(wrapper);
        if(CollUtil.isEmpty(roleMenuRelations)){
            return null;
        }
        List<Long> menuIdList = CollUtil.getFieldValues(roleMenuRelations,"menuId",Long.class);
        LambdaQueryWrapper<Menu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Menu::getId,menuIdList);
        wrapper1.orderByAsc(Menu::getId);
        return menuMapper.selectList(wrapper1);
    }

    @Override
    public void deleteByMenuId(Integer id) {
        LambdaQueryWrapper<RoleMenuRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenuRelation::getMenuId,id);
        roleMenuRelationMapper.delete(wrapper);
    }

    @Override
    public void deleteByRoleId(Integer id) {
        LambdaQueryWrapper<RoleMenuRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenuRelation::getRoleId,id);
        roleMenuRelationMapper.delete(wrapper);
    }

    @Override
    public void save(RoleMenuRelation roleMenuRelation) {
        roleMenuRelationMapper.insert(roleMenuRelation);
    }
}
